<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item :table-form-merge="0.2">
        <el-checkbox v-model="query.option" label="包含下级" />
      </el-form-item>
      <el-form-item label="所属机构：">
        <el-tree-select
          v-model="query.orgId"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgId',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="orgIdChange"
          @select-clear="searchClear"
        />
      </el-form-item>

      <el-form-item label="配送员:" prop="reId">
        <el-select v-model="query.reId" :clearable="true" filterable placeholder="请选择">
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="气瓶状态:" prop="gdStatus">
        <el-select v-model="query.gdStatus" :clearable="true" filterable placeholder="请选择">
          <el-option label="重瓶" :value="1" />
          <el-option label="空瓶" :value="2" />
        </el-select>
      </el-form-item>

      <template v-slot:btns>
        <el-button
          v-permission="[7040102, 1]"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>

    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      :immediate-fetch="true"
      @fetch="fetchData"
    />

    <inventorySearchDetail ref="inventorySearchDetail" />
  </div>
</template>

<script>
  import { csDeliverUserList, storeGroupQuery } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import inventorySearchDetail from './inventorySearchDetail'

  export default {
    name: 'couriers',
    components: { inventorySearchDetail },
    props: {
      goodTList: {
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        query: {
          reId: undefined,
          gdStatus: undefined,
          option: false,
          orgId: ''
        },
        storeMap: [],
        treeData: [],
        userList: [],
        tableData: {
          total: 0,
          column: [
            {
              type: 'index'
            },
            {
              prop: 'storeName',
              align: 'center',
              label: '站点'
            },
            {
              prop: 'rName',
              align: 'center',
              label: '配送员'
            },
            {
              prop: 'gdStatus',
              align: 'center',
              label: '气瓶状态',
              formatter: (row) => {
                return row.gdStatus ? row.gdStatus === 1 ? '重瓶' : row.gdStatus === 2 ? '空瓶' : '' : ''
              }
            },
            {
              prop: 'remark',
              label: '当前库存',
              align: 'center',
              children: []
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters(['orgList', 'userInfo'])
    },
    watch: {
      goodTList: {
        handler() {
          this.tableData.column[this.tableData.column.length - 1].children = this.goodTList.map((item) => ({
            prop: item.specCode,
            align: 'center',
            label: item.specName,
            render: (h, { row, $index }) => {
              return (
                <div>
                  { row[item.specCode] && <el-link underline={false} size='mini' onClick={() => this.showSpecCount(row, item)}>{row[item.specCode]}</el-link>}
                </div>
                )
            }
          }))
        },
        deep: true
      }
    },
    async created() {
      await this.getDetaultTreeData()
    },
    methods: {
      // 获取所属机构数据
      async getDetaultTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        const query = {
          currentPage,
          pageSize,
          params: {
            ...this.query,
            orgId: this.query.option ? 0 : this.query.orgId,
            reType: 2
          }
        }
        if (this.query.option) {
          query.params.reOrgSNNo = this.query.reOrgSNNo
        }
        delete query.params.option
        const res = await storeGroupQuery(query)
        this.tableData.data = res.data.rows
        res.data.rows.forEach((item, index) => {
          if (item.codeCountStr) {
            const list = item.codeCountStr.split(',')
            list.forEach(ele => {
              const l = ele ? ele.split('&') : []
              if (l && l[0] && l[1]) {
                this.tableData.data[index][l[0]] = l[1]
              }
            })
          }
        })
        if (currentPage === 1) this.tableData.total = res.data.total
      },

      search() {
        this.$refs.lbTable.fetch({})
      },
      showSpecCount(row, i) {
        this.$refs.inventorySearchDetail.open({ ...row, specCode: i.specCode, specName: i.specName })
      },
      searchClear() {
        this.query.reId = undefined
        this.userList = []
      },
      orgIdChange(value) {
        this.query.reOrgSNNo = value.orgSNNo
        this.query.reId = undefined
        this.userList = []
        this.getUserList()
      },
      async getUserList() {
        const params = {
          deliveryOrgId: this.query.orgId,
          utype: 1 << 5
        }
        const org = this.treeData.find(item => item.orgId === this.query.orgId)
        if (org && org.orgSNNo) {
          params.deliveryOrgSNNo = org.orgSNNo
        }
        const res = await csDeliverUserList(params)
        this.userList = res.data
      }

    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
</style>
